package com.firefightingiot.firefightingiot.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.firefightingiot.firefightingiot.common.base.BaseService;
import com.firefightingiot.firefightingiot.common.utils.appkit.ConfigKit;
import com.firefightingiot.firefightingiot.common.utils.appkit.FirefightingiotKit;
import com.firefightingiot.firefightingiot.model.DeviceBusiness;
import com.firefightingiot.firefightingiot.model.IpBroadcastFile;
import com.firefightingiot.firefightingiot.support.model.RespEntity;
import com.firefightingiot.firefightingiot.support.mybatisplus.QueryWrapper;
import com.firefightingiot.firefightingiot.support.utils.requestutil.HttpRequestUtil;
import com.firefightingiot.firefightingiot.web.mapper.DeviceBusinessMapper;
import com.firefightingiot.firefightingiot.web.mapper.IpBroadcastFileMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author: YangYu
 * @ClassName: IPBroadCastService
 * @Date: Created in 9:24 2022/3/25
 * @Description: IP广播（沃云）
 */
@Service
public class IPBroadCastService extends BaseService {

    HttpResponse httpResponse;
    @Resource
    IPBroadCastAsyncService ipBroadCastAsyncService;
    @Resource
    IpBroadcastFileMapper ipBroadcastFileMapper;

    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;

    /**
     * @Author YangYu
     * @Description 上传音乐到中转服务器
     * @Date Created in 10:51 2022/3/25
     * @Param [file]
     */

    public RespEntity uploadMusic(MultipartFile file,String homeId) throws IOException, InterruptedException {

        //校验文件是否存在
        int count = ipBroadcastFileMapper.selectCount(new QueryWrapper<IpBroadcastFile>().eq("file_name",file.getOriginalFilename()));
        if (count>0){
            return RespEntity.fail("文件已存在，请重新上传或修改文件名称!");
        }
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("homeId",homeId);
        String ip = "";
        String methodPath = "";
        ip = ConfigKit.getStr("IPBroadcast","config");
        methodPath = FirefightingiotKit.getStr("uploadmusic","IPBroadcast");
        String domain = ip + methodPath;
        String xml = "";
        httpResponse = HttpRequest.post(domain)
                .form("file",file.getBytes(),file.getOriginalFilename())
                .form("serverdir","CloudMusic")
                .execute();
        xml = httpResponse.body();
        JSONObject jsonObject = JSONUtil.parseObj(xml);
        if (jsonObject.getStr("code").equals("1")){
            IpBroadcastFile ipBroadcastFile = new IpBroadcastFile();
            ipBroadcastFile.setId(UUID.randomUUID().toString());
            ipBroadcastFile.setFileName(file.getOriginalFilename());
            ipBroadcastFile.setHomeId(jsonParam.getStr("homeId"));
            ipBroadcastFile.setServerMusicId("y");
            ipBroadcastFile.setCreatetime(DateUtil.now());
            ipBroadcastFileMapper.insert(ipBroadcastFile);
            //更新音乐临时ID变换的数据
            Thread.sleep(8000);
            updateServerMusicId(jsonParam);
            return RespEntity.success();
        }else {
            return RespEntity.fail();
        }
    }

    /**
     * @Author YangYu
     * @Description 获取音乐文件
     * @Date Created in 13:47 2022/3/28
     * @Param [jsonParam]
     */

    public RespEntity getMusicFileList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        List<IpBroadcastFile> fileList = ipBroadcastFileMapper.selectList(new QueryWrapper<IpBroadcastFile>().eq("home_id",jsonParam.getStr("homeId")));
        return RespEntity.success(fileList);
    }
    /**
     * @Author YangYu
     * @Description 异步更新文件
     * @Date Created in 12:03 2022/3/25
     * @Param [jsonParam]
     */
    public RespEntity updateServerMusicId(JSONObject jsonParam){
        //获取全部文件
        List<IpBroadcastFile> fileList = ipBroadcastFileMapper.selectList(new QueryWrapper<IpBroadcastFile>().eq("home_id",jsonParam.getStr("homeId")));
        //获取服务器上全部文件名
        JSONObject allMusicsInfo = IPBroadCast(jsonParam,"IPBroadcast","getAllMusicsInfo","IPBroadcast","GET");
        JSONArray musicInfoArray = allMusicsInfo.getJSONArray("musicinfoarray");
        //更新数据
        List<IpBroadcastFile> updateFileList = new ArrayList<>();
        for (IpBroadcastFile file : fileList){
            for (Object object : musicInfoArray){
                JSONObject jsonObject = (JSONObject)object;
                if (file.getFileName().equals(jsonObject.getStr("cpfilename"))){
                    if (!file.getServerMusicId().equals(jsonObject.getStr("servermusicid"))){
                        file.setServerMusicId(jsonObject.getStr("servermusicid"));
                        updateFileList.add(file);
                    }
                }
            }
        }
        ipBroadcastFileMapper.batchUpdate(updateFileList);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 删除音乐文件
     * @Date Created in 16:17 2022/3/25
     * @Param [jsonParam]
     */

    public RespEntity deleteMusic(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        //删除中转服务器文件
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cpfilename",jsonParam.getStr("fileName"));
        jsonObject.put("pbydirname","cloudmusic");
        jsonObject.put("model",1);
        //调用中转服务器
        JSONObject msg = IPBroadCast(jsonObject,"IPBroadcast","servermusic","IPBroadcast","DELETE");
        if (msg.getStr("code").equals("1")){
            //删除数据库音乐文件
            ipBroadcastFileMapper.deleteById(jsonParam.getStr("id"));
            return RespEntity.success();
        }else {
            return RespEntity.fail("文件删除失败!");
        }
    }


    /**
     * @Author YangYu
     * @Description 批量播放音乐
     * @Date Created in 16:32 2022/3/25
     * @Param [jsonParam]
     */

    public RespEntity playMusicByList(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));

        //组装数据
        JSONObject json = new JSONObject();
        //遍历设备id
        JSONArray deviceidarray = new JSONArray();
        for (Object o : jsonParam.getJSONArray("deviceidarray")){
            deviceidarray.add(o);
        }
        //遍历音乐id
        JSONArray musicidlist = new JSONArray();
        for (Object o : jsonParam.getJSONArray("musicidlist")){
            musicidlist.add(o);
        }
        json.put("deviceidarray",deviceidarray);
        json.put("musicidlist",musicidlist);
        json.put("model",jsonParam.getInt("model"));
        //调用中转服务器
        JSONObject msg = IPBroadCast(json,"IPBroadcast","postPlayMusicByList","IPBroadcast","POST");
        if (msg.getStr("byerrorcode").equals("3")){
            return RespEntity.success();
        }else if (msg.getStr("byerrorcode").equals("1")){
            return RespEntity.fail("没有一个设备可以播放，可能是优先不够，也可能是设备全部掉线了,也可能是中转不在线!  设备编号为:"+msg.getJSONArray("wpdevid").toString());
        }else if (msg.getStr("byerrorcode").equals("2")){
            return RespEntity.fail("歌曲文件不存在了!  设备编号:"+msg.getJSONArray("wpdevid").toString());
        }else if (msg.getStr("byerrorcode").equals("4")){
            return RespEntity.fail("部份设备成功,部份设备播放不成功!  设备编号:"+msg.getJSONArray("wpdevid").toString());
        }else if (msg.getStr("byerrorcode").equals("5")){
            return RespEntity.fail("外置音源不存在!  设备编号:"+msg.getJSONArray("wpdevid").toString());
        }else {
            return RespEntity.fail("其他错误!  设备编号为:"+msg.getJSONArray("wpdevid").toString());
        }
    }

    /**
     * @Author YangYu
     * @Description 批量停止播放
     * @Date Created in 14:03 2022/3/28
     * @Param [jsonParam]
     */

    public RespEntity stopMusic(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));

        //组装数据
        JSONObject json = new JSONObject();
        //遍历设备id
        JSONArray deviceidarray = new JSONArray();
        for (Object o : jsonParam.getJSONArray("deviceidarray")){
            deviceidarray.add(o);
        }
        json.put("deviceidarray",deviceidarray);
        //调用中转服务器
        JSONObject msg = IPBroadCast(json,"IPBroadcast","postStopMusic","IPBroadcast","POST");
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 批量播放TTS
     * @Date Created in 17:01 2022/3/25
     * @Param [jsonParam]
     */

    public RespEntity ttsPlayMusic(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        //组装数据
        JSONObject json = new JSONObject();
        //遍历设备id
        String deviceidarray = "[";
        for (Object o : jsonParam.getJSONArray("deviceidarray")){
            String s1 = o.toString();
            s1 = '"'+s1+'"';
            deviceidarray = deviceidarray+s1;
        }
        deviceidarray = deviceidarray+"]";
        json.put("text",jsonParam.getStr("text"));
        json.put("times",jsonParam.getInt("times"));
        json.put("deviceidarray",deviceidarray);
        JSONObject msg = IPBroadCast(json,"IPBroadcast","postttsplaymusic","IPBroadcast","POST");
        if (msg.getStr("code").equals("1")){
            return RespEntity.success();
        }else if (msg.getStr("code").equals("2101")){
            return RespEntity.fail("都没播放成功!");
        }else {
            return RespEntity.fail("部分设备播放成功!  成功设备编号为:"+msg.getJSONArray("wpdevid").toString());
        }
    }

    /**
     * @Author YangYu
     * @Description 监听设备
     * @Date Created in 17:14 2022/3/25
     * @Param [jsonParam]
     */

    public RespEntity monitor(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        JSONObject msg = IPBroadCast(jsonParam,"IPBroadcast","postMonitor","IPBroadcast","POST");
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 停止监听
     * @Date Created in 17:21 2022/3/25
     * @Param [jsonParam]
     */

    public RespEntity stopMonitor(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        JSONObject msg = IPBroadCast(jsonParam,"IPBroadcast","postStopMonitor","IPBroadcast","POST");
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 调节音量
     * @Date Created in 17:24 2022/3/25
     * @Param [jsonParam]
     */

    public RespEntity setvol(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        //组装数据
        JSONObject json = new JSONObject();
        //遍历设备id
        JSONArray deviceidarray = new JSONArray();
        for (Object o : jsonParam.getJSONArray("deviceidarray")){
            DeviceBusiness deviceBusiness = new DeviceBusiness();
            deviceBusiness.setLedVolume(jsonParam.getStr("vol"));
            deviceBusinessMapper.update(deviceBusiness, new QueryWrapper<DeviceBusiness>().eq("number", o.toString()));
            deviceidarray.add(o);
        }
        json.put("deviceidarray",deviceidarray);
        json.put("vol",jsonParam.getInt("vol"));
        JSONObject msg = IPBroadCast(json,"IPBroadcast","postSetvol","IPBroadcast","POST");
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 获取当前设备状态信息
     * @Date Created in 9:25 2022/4/6
     * @Param [jsonParam]
     */

    public RespEntity getDevicesInfo(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        JSONArray msgArray = IPBroadCastJsonArray(jsonParam,"IPBroadcast","getAllDevicesInfo","IPBroadcast","GET");
        for (Object o : msgArray){
            JSONObject jsonObject = (JSONObject) o;
            if (jsonObject.getStr("undevid").equals(jsonParam.getStr("number"))){
                return RespEntity.success(jsonObject);
            }
        }
        return RespEntity.fail("服务端设备不存在!");
    }

}
